<template>
 

  <div class="prescription-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <input 
        v-model="searchKeyword" 
        placeholder="挂号ID" 
        class="search-input"
      >
      <button class="refresh-btn" @click="loadData">搜索</button>
    </div>

    <!-- 头部信息（改为处理数组） -->
    <div 
      class="header-section" 
      v-for="(prescription, index) in prescriptions" 
      :key="index"
      v-if="prescriptions.length > 0"
    >
      <div class="info-row">
        <span class="label">挂号单号：</span>
        <span class="value">{{ prescription.regId }}</span>
        <span class="label" style="margin-left: 40px">医生姓名：</span>
        <span class="value">{{ prescription.userName }}</span>
      </div>
      <div class="info-row">
        <span class="label">科室名称：</span>
        <span class="value">{{ prescription.deptName }}</span>
        <span class="label" style="margin-left: 40px">患者姓名：</span>
        <span class="value">{{ prescription.patientName }}</span>
      </div>
      <div class="info-row">
        <span class="label">就诊时间：</span>
        <!-- 动态绑定就诊时间 -->
        <span class="value">{{ formatDate(prescription.careDate) }}</span>
      </div>
    <!-- 其他部分保持不变 -->
  <el-button type="success" @click="checkAll(true)"><el-icon><Finished /></el-icon>全选</el-button>
  <el-button type="primary" @click="checkAll(false)"><el-icon><Finished /></el-icon>取消全选</el-button>
      <el-button type="danger" @click="setStatus"><el-icon><MessageBox /></el-icon>确定发药</el-button>
      <!-- 药品表格（嵌套在循环内部） -->
      <hr>
      <table class="medicine-table">

        <thead>
         
          <tr>
            <th></th>
            <th>序号</th>
            <th>药品名称</th>
            <th>数量</th>
            <th>单价（元）</th>
            <th>金额（元）</th>
            <th>备注</th>
            <th>状态</th>
          </tr>
        </thead>
        <tbody>
          <!-- 过滤出药品类型（假设 itemType=0 是药品） -->
          <tr 
            v-for="(item, idx) in prescription.hisCareOrderItems.filter(x => x.itemType === '0')" 
            :key="idx"
          >
          <td><input type="checkbox" @change="handleSingleCheck(item)" v-model="item.checked"/></td>
            <td>{{ idx + 1 }}</td>
            <td>{{ item.itemName }}</td>
            <td>{{ item.num }}</td>
            <td>{{ item.price }}</td>
            <td>{{ Number(item.num * item.price).toFixed(2) }}</td>
            <td>{{ item.remark || '-' }}</td>
            <td>
              <span class="status-tag">{{ item.status==3?"已完成":""}}
                {{ item.status==2?"已退费":""}}
                {{ item.status==1?"已支付":""}}
                {{ item.status==0?"未支付":""}}
              </span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 空状态提示 -->
    <div v-if="prescriptions.length === 0" class="empty-tip">
      暂无处方数据
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed,watch } from 'vue';
import http from '@/http';
import {
    Delete,
    Edit,
    Search,
    Share,
    Upload,
    CirclePlus,
} from "@element-plus/icons-vue"; //导入图标
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const searchKeyword = ref('');
const prescriptions = ref([]); // 改为数组类型
// 在药品数据中添加 checked 状态
const selectedItems = ref(new Set()); // 存储选中项的ID
//确定发药
// 修改后的发药方法
function setStatus() {
  ElMessage({
    message: '正在进行发药.',
    type: 'success',
  })

  // 将 Set 转换为 Array
  const itemIds = Array.from(selectedItems.value)
  
  http.post("/careorderitem/setStatus", itemIds, {
    headers: {
      'Content-Type': 'application/json' // 明确指定请求头
    }
  }).then((res) => {
    ElMessage({
    message: '发药成功.',
    type: 'success',
  })
    console.log("操作成功", res)
  }).catch((err) => {
    ElMessage('发药失败')
    console.error("操作失败", err)
  })
}
//复选框
function checkedCK(item,index){
console.log(item,index)
}

// 加载数据
const loadData = async () => {
  try {
    const res = await http.get(`/hiscarehistory/getRegIdHIstory?regId=${searchKeyword.value}`);
       // 深度初始化 checked 状态
    prescriptions.value = (Array.isArray(res) ? res : []).map(prescription => ({
      ...prescription,
      hisCareOrderItems: prescription.hisCareOrderItems?.map(item => ({
        ...item,
        checked: false // 添加初始化的 checked 属性
      })) || []
    }));
  } catch (error) {
    prescriptions.value = [];
    console.error('加载数据失败:', error);
  }
};

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
};
// 修正后的全选方法（确保深层响应式）
const checkAll = (isCheck: boolean) => {
  alert("A")
  prescriptions.value = prescriptions.value.map(prescription => {
    // 创建新的处方对象
    const newPrescription = { ...prescription }
    
    // 深层处理药品项（关键步骤）
    newPrescription.hisCareOrderItems = (prescription.hisCareOrderItems || []).map(item => ({
      ...item,
      checked: isCheck
    }))
    
    return newPrescription
  })
  
  // 强制视图更新（备选方案）
   prescriptions.value = [...prescriptions.value]
   console.log("prescriptions",prescriptions.value)
}

// 单个复选框点击处理
const handleSingleCheck = (item) => {
  if (item.checked) {
    selectedItems.value.add(item.itemId);
  } else {
    selectedItems.value.delete(item.itemId);
  }
  console.log(selectedItems.value)
};

//监听选中状态变化（可选）
watch(prescriptions, (newVal) => {
  const allItems = newVal.flatMap(p => p.hisCareOrderItems);
  const selected = allItems.filter(item => item.checked);
  selectedItems.value = new Set(selected.map(item => item.itemId));
  console.log("监听状态",selectedItems.value)
}, { deep: true });
  </script>
  
  <style scoped>
  .medicine-table td:first-child {
  text-align: center;
  width: 40px;
}
  .prescription-container {
    padding: 20px;
    background: #fff;
    font-family: 'Microsoft YaHei', sans-serif;
  }
  
  .header-section {
    border: 1px solid #EBEEF5;
    padding: 15px;
    margin-bottom: 20px;
  }
  
  .info-row {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
  }
  
  .label {
    color: #909399;
    min-width: 70px;
  }
  
  .value {
    color: #606266;
    margin-right: 30px;
  }
  
  .filter-section {
    display: flex;
    justify-content: space-between;
    margin-bottom: 15px;
  }
  
  .status-filter {
    display: flex;
    gap: 10px;
  }
  
  .status-btn {
    padding: 6px 15px;
    border: 1px solid #DCDFE6;
    border-radius: 4px;
    background: #FFF;
    color: #606266;
    cursor: pointer;
  }
  
  .status-btn.active {
    border-color: #409EFF;
    background: #409EFF;
    color: white;
  }
  
  .prescription-summary {
    color: #606266;
    font-size: 14px;
  }
  
  .total-amount {
    color: #F56C6C;
    font-weight: bold;
  }
  
  .medicine-table {
    width: 100%;
    border-collapse: collapse;
    border: 1px solid #EBEEF5;
  }
  
  .medicine-table th {
    background: #FAFAFA;
    color: #909399;
    font-weight: 500;
    padding: 12px;
    border: 1px solid #EBEEF5;
    text-align: left;
  }
  
  .medicine-table td {
    padding: 12px;
    border: 1px solid #EBEEF5;
    color: #606266;
  }
  
  .status-tag {
    display: inline-block;
    padding: 4px 8px;
    background: #f0f9eb;
    color: #67C23A;
    border-radius: 4px;
    font-size: 12px;
  }
  
  /* 交互效果 */
  .status-btn:hover {
    background: #F5F7FA;
  }
  
  .status-btn.active:hover {
    background: #66B1FF;
  }
  /* 添加斑马纹效果 */
  .medicine-table tr:nth-child(even) {
    background-color: #fafafa;
  }
  
  /* 添加加载状态 */
  .loading-mask {
    position: absolute;
    background: rgba(255,255,255,0.8);
  }
  </style>